import chadanRequest from "./chadan-request.js";
import { getToken } from "./chadan-login.js";
import { sleep } from "../utils/index.js";

export async function getOrders() {
  const res = await chadanRequest({
    url: 'https://vipapi.chadanwang.com/scalperEquityOrder/queryPool',
    method: 'post',
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    data: {
      pageNum: 1,
      pageSize: 3,
      brand: 12,
      exclusiveCity: '',
      JSESSIONID: await getToken(),
    }
  });
  const body = res.data;

  // const body = {"errorMsg":"OK","data":{"total":1,"list":[{"id":12913651,"logo":"http://oss.chadanwang.com/scalperEquityBrandLogo/海威在线接单/星巴克","brandName":"星巴克","officialPrice":63,"price":47.1,"products":[{"orderId":12913651,"productId":4120,"productName":"测试美式咖啡 请勿下单","detail":"测试美式咖啡 请勿下单","productDescription":"中杯,微热,标准","amount":2,"isShowDetail":"YES"},{"orderId":12913651,"productId":4121,"productName":"测试巴旦木拿铁","detail":"测试巴旦木拿铁","productDescription":"中杯,冰,标准,巴旦木奶","amount":1,"isShowDetail":"YES"}],"createTime":"2025-11-05 15:57:53","now":"2025-11-05 15:59:59","duration":2,"brandId":12,"groupId":40,"detail":"地区：山东省 烟台市\r\n门店编号：19559\r\n门店：烟台观海路咖啡店\r\n门店地址：烟台市莱山区观海路277号佳世客一层\r\n就餐方式：堂食"}],"pageNum":1,"pageSize":10,"size":1,"startRow":1,"endRow":1,"pages":1,"prePage":0,"nextPage":0,"isFirstPage":true,"isLastPage":true,"hasPreviousPage":false,"hasNextPage":false,"navigatePages":8,"navigatepageNums":[1],"navigateFirstPage":1,"navigateLastPage":1,"firstPage":1,"lastPage":1},"errorCode":200}

  return body.data?.list || [];
}

export async function fetchOrder(orderId){
  const res = await chadanRequest({
    url: 'https://vipapi.chadanwang.com/scalperEquityOrder/fetchOrder',
    method: 'POST',
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    data: {
      orderId,
      JSESSIONID: await getToken(),
    }
  });

  const data = res.data;

  // const data = {"errorCode":200,"errorMsg":"SE20251105155753715521178","expire":null,"ok":true};

  if(data?.errorCode === 200) {
    return data.errorMsg;
  }

  throw new Error(`${orderId} 接单失败 ，${JSON.stringify(data)}`);
}

export async function dropOrder(order, failReason = '暂无下单渠道'){
  // {errorCode: 9003, errorMsg: '请2秒后再上报', expire: null, ok: false}
  console.warn(`2秒后开始弃单：${failReason}，${JSON.stringify(order)}`);
  await sleep(2000);
  const res = await chadanRequest({
    url: 'https://vipapi.chadanwang.com/scalperEquityOrder/reportOrder',
    method: 'POST',
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    data: {
      id: order.id,
      brandId: order.brandId,
      orderStatus: 'CLOSE',
      failReason,
      JSESSIONID: await getToken(),
    }
  });
  const data = res.data;
  console.warn(`弃单结果：${JSON.stringify(data)}`)
  // {"errorCode":200,"errorMsg":"请求通过","expire":null,"ok":true}
  if(data?.errorCode !== 200) {
    throw new Error(`${order.id} 弃单失败 ，${JSON.stringify(data)}`);
  }
}
